package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.model.Answer;
import cn.tedu.knows.portal.service.IAnswerService;
import cn.tedu.knows.portal.vo.AnswerVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.w3c.dom.stylesheets.LinkStyle;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2022-03-04
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {
    @Autowired
    private IAnswerService answerService;

    @PostMapping("")
    //@PreAuthorize("hasRole('ROLE_TEACHER')")

    @PreAuthorize("hasAuthority('/question/answer')")
    public String postAnswer(@Validated AnswerVO answerVO,
                             BindingResult result,
                             @AuthenticationPrincipal UserDetails user){
        log.debug("接收表单信息:{}",answerVO);
        if (result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            return msg;
        }
        answerService.saveAnswers(answerVO,user.getUsername());
        return "ok";
    }
    @GetMapping("/question/{id}")
    public List<Answer> questionAnswers(@PathVariable Integer id){
        List<Answer>answers=answerService.getAnswerByQuestionId(id);
        return answers;
    }


}
